﻿using Iworld.Backstage.Framework;
using Iworld.Backstage.Framework.AdministratorService;
using Iworld.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Iworld.Backstage
{
    public partial class MainPage : UserControl,IMainPage<Page,Pop>
    {
        public MainPage()
        {
            InitializeComponent();
            client.KeepHeartbeatCompleted += KeepHeartbeatCompleted;
            Storyboard sb = new Storyboard();
            sb.Duration = new Duration(new TimeSpan(0, 0, 5));
            sb.Completed += sb_Completed;
            sb.Begin(); 
        }

        void KeepHeartbeatCompleted(object sender, KeepHeartbeatCompletedEventArgs e)
        {
            isDoing = false;
            if(!e.Result.Success)
            {
                settingOut = true;
                ErrorPrompt ep = new ErrorPrompt() { Info = e.Result.Error };
                ep.Closed += (s, a) => {
                    BackstageViewModelService.Current.JumpToDefaultPage();
                    settingOut = false;
                };
                ep.Show();
            }else
            {
               DataManager.SetValue(DataKey.CountOfUsersInClient,e.Result.Info.CountOfUsersInClient);
               DataManager.SetValue(DataKey.CountOfUsersInBackstage, e.Result.Info.CountOfUsersInBackstage);
              if(e.Result.Info.CountOfWithdrawals > 0)
              {
                  win_UnreadNotices_Text.Text = string.Format("有 {0} 条提现记录需要你处理！~",
                      e.Result.Info.CountOfWithdrawals);
                  win_UnreadNotices.Visibility = System.Windows.Visibility.Visible;
                  music_dingdong.Stop();
                  music_dingdong.Play();
              }
              
            }
        }
        //int i = 0;
        void sb_Completed(object s, EventArgs a)
        {
            if (!isDoing && !settingOut &&  DataManager.HaveValue<AdministratorExport>(DataKey.Administrator_Info))
            {
               client.KeepHeartbeatAsync(new KeepHeartbeatImport() { Token = DataManager.GetValue<AdministratorExport>(DataKey.Administrator_Info).Token });
               isDoing = true; 
            }
            Storyboard ssb = (Storyboard)s;
            ssb.Begin();
        }

        bool settingOut = false;
        bool isDoing = false;
        AdministratorServiceClient client = new AdministratorServiceClient();

        /// <summary>
        /// 显示目标子界面
        /// </summary>
        /// <param name="userControl">所要显示的子界面</param>
        public void Show(UIElement userControl)
        {
            body.Children.Clear();
            body.Children.Add(userControl);
        }

        /// <summary>
        /// 关闭主窗口
        /// </summary>
        public void CloseMainWindow()
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
                App.Current.MainWindow.Close();
            }
        }

        private void CloseSmallWindow(object sender, RoutedEventArgs e)
        {
            win_UnreadNotices.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void DoWith(object sender, MouseButtonEventArgs e)
        {
            win_UnreadNotices.Visibility = System.Windows.Visibility.Collapsed;
            BackstageViewModelService.Current.JumpTo(Page.提现记录);
        }

        /// <summary>
        /// 注册可跳转界面
        /// </summary>
        public void RegisterViews(ViewModelServiceBase<Page, Pop> service)
        {
            //获取目标程序集
            Assembly assembly = Assembly.GetExecutingAssembly();

            #region 注册可跳转界面

            assembly.GetTypes()
                .Where(x => x.GetCustomAttributes(true).Any(t => t is Iworld.ViewModel.ViewAttribute))
                .ToList().ForEach(x =>
                {
                    var attribute = x.GetCustomAttributes(true).First(t => t is Iworld.ViewModel.ViewAttribute)
                        as Iworld.ViewModel.ViewAttribute;
                    service.RegisterPage((Page)attribute.Page
                        , x.Name
                        , attribute.IsDefault
                        , new UIElementCreater(() =>
                        {
                            return assembly.CreateInstance(x.FullName) as UIElement;
                        }));
                });

            #endregion

            #region 注册弹窗

            assembly.GetTypes()
                .Where(x => (x.GetInterfaces().Any(t => t == typeof(IPop)))
                    && (x.GetCustomAttributes(true).Any(t => t is PopAttribute)))
                .ToList().ForEach(_type =>
                {
                    PopAttribute attribute = _type.GetCustomAttributes(true)
                        .First(x => x is PopAttribute) as PopAttribute;
                    service.RegisterPop((Pop)attribute.Pop
                        , new PopCreater(() =>
                        {
                            return assembly.CreateInstance(_type.FullName) as IPop;
                        }));
                });

            #endregion
        }
    }
}
